package top.suven.http.oauth.validator;

import top.suven.http.oauth.token.OAuthAuthxRequest;
import top.suven.http.oauth.vo.OAuthParameter;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 2018-08-01
 * <p/>
 * response_type=code   finish
 *  AbstractOauthTokenValidator
 *  客户端	客户详细资料 抽像模块类，用于公共验证和获取客户用户的信息；
 *  将通用的行为(方法) 位于此  response_type = 'code'
 * response_type=code&scope=read,write&client_id=[client_id]&redirect_uri=[redirect_uri]&state=[state]
 * @author suven.wang Client Credentials
 */
public class ResponseTypeClientDetailsValidator extends AbstractOAuthResponseTypeValidator {

    private static final Logger logger = LoggerFactory.getLogger(ResponseTypeClientDetailsValidator.class);

    public ResponseTypeClientDetailsValidator(OAuthAuthzRequest oauthRequest) {
        //
        super(oauthRequest);
    }

    /*
    *  grant_type="authorization_code"
    *  ?response_type=code&scope=read,write&client_id=[client_id]&redirect_uri=[redirect_uri]&state=[state]
    * */
    @Override
    public boolean validateSelf() throws OAuthSystemException {
        //validate redirect_uri
        if(!this.validateResponseType()){
            return false;
        }
//        if(!this.validateClientSecret()){
//            return false;
//        }
        if(!this.validateScope()){
            return false;
        }
        if(!this.validateState(this.getState())){
            return false;
        }
        // 验证用户是否已经登陆;
        if(!validateLogin()){
            return false;
        }
        return true;
    }



    private boolean validateLogin(){
        final String redirectUri = oauthRequest.getRedirectURI();
        try {
            OAuthParameter parameter = ((OAuthAuthxRequest)oauthRequest).getOAuthParameter();
            if(null == parameter){
                OAuthResponse response =  this.expiredTokenResponse("",redirectUri);
                return false;
            }
            boolean isLogin = this.checkLogin(parameter.getUserId(),parameter.getRefreshToken());
            return isLogin;
        }catch (Exception e){
            return false;
        }

    }


}
